import router from './router'
import cookie from 'js-cookie'
import { Message } from 'element-ui'
import store from '@/store'

export const addRouter = (menuList = [], routes = []) => {
  menuList.forEach((item, i) => {
    if (item.children && item.children.length > 0) {
      addRouter(item.children, routes)
    } else {
      routes.push({
        name: item.name,
        path: item.url,
        component: () => import(`@/views${item.url}`),
      })
    }
  })
  return routes
}

// 递归添加路由
// const addRouter = (menuList = [], routes = []) => {
//   for (let i in menuList) {
//     if (menuList[i].children && menuList[i].children.length > 0) {
//       addRouter(menuList[i].children, routes)
//     } else {
//       routes.push({
//         meta: {
//           reset: menuList[i].reset,
//         },
//         name: menuList[i].name,
//         path: menuList[i].url,
//         // 路由文件写在url下，如/sys/user就在sys下创建user.vue文件
//         component: () => import(`@/views${menuList[i].url}`),
//       })
//     }
//   }
//   return routes
// }

router.beforeEach(async (to, from, next) => {
  const token = cookie.get('token')
  // 如果是访问登录界面，如果token信息存在，代表已登录过，跳转到主页
  if (to.path === '/login') {
    if (token) {
      Message({
        message: '请勿重复登录！',
        type: 'error',
      })
      next('/')
      console.log(to.path)
      return
    }
    next()
    return
  }

  // 如果访问非登录界面，token不存在，则跳转到登录界面
  if (!token) {
    Message({
      message: '请先登录！',
      type: 'error',
    })
    next({ path: '/login' })
    return
  }

  // 加载动态菜单和路由
  const menuTree = store.state.navMenu.navTree

  if (!menuTree) {
    const menuList = await store.dispatch('navMenu/getMenuList')

    if (!menuList) {
      console.log('暂无数据')
      next()
      return
    }

    let routes = await addRouter(menuList)

    for (let childRoutes of routes) {
      router.addRoute('首页', childRoutes)
    }

    next({ ...to, replace: true })

    return
  }

  next()
})
